//
//  LFLoginViewController.m
//  LoveFruit
//
//  Created by 张令林 on 16/9/22.
//  Copyright © 2016年 张令林. All rights reserved.
//

#import "LFLoginViewController.h"
#import "LFTabBarController.h"
#import "UIColor+Addition.h"

#define Appkey @"1762cf5e5aee8"

#define AppSecret @"9ea691fdc8c3c2f2c61cf121e5cd1482"

#import "LFAccountManger.h"

#import <SMS_SDK/SMSSDK.h>

#import "AlertView.h"

@interface LFLoginViewController () <UITextFieldDelegate>

@property (nonatomic,weak) UITextField *phoneText;

@property (nonatomic,weak) UITextField *codeText;

@end

@implementation LFLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithHex:0xefefef];
    
    [self setUpNavi];
    
    //调用初始化方法
    [self setUpUI];
    
}

//判断手机号码是否正确
- (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    //    电信号段:133/153/180/181/189/177
    //    联通号段:130/131/132/155/156/185/186/145/176
    //    移动号段:134/135/136/137/138/139/150/151/152/157/158/159/182/183/184/187/188/147/178
    //    虚拟运营商:170
    
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}

- (void)setUpNavi
{
    self.navigationItem.title = @"手机登录";
    
    //设置返回按钮
//    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"btn_backItem"] style:UIBarButtonItemStylePlain target:self action:@selector(leftClick)];
//    
//    self.navigationItem.leftBarButtonItem = leftItem;
}

- (void)leftClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

//获取验证码
- (void)getCode
{
    if([self isMobileNumber:self.phoneText.text])
    {
    NSLog(@"获取验证码");
    [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.phoneText.text
                                   zone:@"86"
                       customIdentifier:nil
                                 result:^(NSError *error){
     if (!error) {
         NSLog(@"获取验证码成功");
     } else {
         NSLog(@"错误信息：%@",error);
         
         [self showMessage:@"验证码获取错误"];
     }}];
    }
    else
    {
        [self showMessage:@"手机号码输入有误"];
    }
}

#pragma mark 初始化方法
- (void)setUpUI
{
    UIImageView *backView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"6_photo"]];
    [self.view addSubview:backView];
    
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.edges.equalTo(self.view);
        
    }];
    
    UITextField *phoneField = [[UITextField alloc] init];
    [self.view addSubview:phoneField];
    UIColor *color = [UIColor colorWithHex:0xbebebe];
    phoneField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入您的手机号码" attributes:@{NSForegroundColorAttributeName:color}];
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 45)];
    phoneField.leftView = view1;
    phoneField.leftViewMode = UITextFieldViewModeAlways;
    phoneField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    [phoneField setFont:[UIFont systemFontOfSize:16]];
    
    //这句代码会改变所有光标颜色
    [[UITextField appearance] setTintColor:[UIColor colorWithWhite:0.5 alpha:1]];
    
    self.phoneText = phoneField;
    
    //设置约束
    [phoneField mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.view);
        make.top.offset(100);
        make.height.offset(50);
    }];
    
    UIButton *getButton =  [UIButton buttonLRWithImgName:nil title:@"获取验证码" color:[UIColor blackColor] forSize:13 target:self action:@selector(getCode) forControlEvents:UIControlEventTouchUpInside];
    [getButton setBackgroundImage:[UIImage imageNamed:@"v2_coupon_verify_normal"] forState:UIControlStateNormal];
    getButton.adjustsImageWhenHighlighted = NO;
    getButton.layer.cornerRadius = 5;
    getButton.layer.masksToBounds = YES;
    
    [self.view addSubview:getButton];
    
    [getButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.right.offset(-10);
        make.width.offset(100);
        make.left.equalTo(phoneField.mas_right).offset(10);
        make.top.equalTo(phoneField.mas_top).offset(5);
        make.bottom.equalTo(phoneField.mas_bottom).offset(-5);
        
    }];

    
    
    CGFloat xscale = 1/[UIScreen mainScreen].scale;
    
    UIImageView *lineView = [[UIImageView alloc] init];
    lineView.backgroundColor = [UIColor colorWithHex:0xe0e0e0];
    [self.view addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.equalTo(self.view);
        make.height.offset(xscale);
        make.top.equalTo(phoneField.mas_bottom);
        
    }];
    phoneField.delegate = self;
    
    UITextField *codeField = [[UITextField alloc] init];
    [self.view addSubview:codeField];
    //UIColor *color = [UIColor colorWithHex:0xbebebe];
    codeField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入短信验证码" attributes:@{NSForegroundColorAttributeName:color}];
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 45)];
    codeField.leftView = view2;
    codeField.leftViewMode = UITextFieldViewModeAlways;
    [codeField setFont:[UIFont systemFontOfSize:16]];
    codeField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //设置约束
    [codeField mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(self.view);
        make.top.equalTo(lineView.mas_bottom);
        make.height.offset(50);
    }];
    
    self.codeText = codeField;
    
    UIImageView *lineView1 = [[UIImageView alloc] init];
    lineView1.backgroundColor = [UIColor colorWithHex:0xe0e0e0];
    [self.view addSubview:lineView1];
    
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(self.view);
        make.height.offset(xscale);
        make.top.equalTo(codeField.mas_bottom);
        
    }];
    
//    UIButton *button = [uibu]
    UIButton *addBut =  [UIButton buttonLRWithImgName:nil title:@"确定" color:[UIColor blackColor] forSize:13 target:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    [addBut setBackgroundImage:[UIImage imageNamed:@"v2_coupon_verify_normal"] forState:UIControlStateNormal];
    
    addBut.adjustsImageWhenHighlighted = NO;
    
    addBut.layer.cornerRadius = 5;
    addBut.layer.masksToBounds = YES;
    
    
    [self.view addSubview:addBut];

    [addBut mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.offset(10);
        make.right.offset(-10);
        make.height.offset(50);
        make.top.equalTo(codeField.mas_bottom).offset(30);
        
    }];
    
    //写一个协议
    
    UILabel *descLable = [UILabel labelWithText:@"登陆即表示你同意爱鲜蜂" andTextColor:[UIColor blackColor] andFontSize:14];
    [self.view addSubview:descLable];
    
    //设置约束
    [descLable mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(self.view).offset(-50);
        make.top.equalTo(addBut.mas_bottom).offset(15);
        
    }];
    
    
    UIButton *agreeBut = [UIButton buttonLRWithImgName:nil title:@"《用户协议》" color:[UIColor yellowColor] forSize:14 target:self action:@selector(agreeButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:agreeBut];
    
    [agreeBut mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerY.equalTo(descLable);
        make.left.equalTo(descLable.mas_right);
        
    }];
    
    //第三方登录
    
    //直接跳转到首页,测试使用
    //[self login];
}


- (void)agreeButton
{
    
}

//监听输入字符的个数改变

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField.text.length <11)
    {
        return YES;
    }
    else
    {
        return NO;
    }
    NSLog(@"%ld",textField.text.length);
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //[self login];
}

#pragma mark 进入主页面
- (void)login
{

    [SMSSDK commitVerificationCode:self.codeText.text phoneNumber:self.phoneText.text zone:@"86" result:^(NSError *error) {
        
        if (!error) {
            
            LFAccountManger *accountMnager = [LFAccountManger defaultManger];
            accountMnager.phone = self.phoneText.text;
            NSLog(@"验证成功");
            //[SVProgressHUD showWithStatus:@"成功"];
            [self buttonClicked:1];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                
                LFTabBarController *vc = [[LFTabBarController alloc] init];
                
                [UIView animateWithDuration:1 animations:^{
                    self.view.transform = CGAffineTransformMakeScale(2, 2);
                    self.view.alpha = 0;
                } completion:^(BOOL finished) {
                    [self presentViewController:vc animated:YES completion:^{
                        [self.view removeFromSuperview];
                        [self removeFromParentViewController];
                        [SVProgressHUD dismiss];
                    }];
                }];
                
            });
            
        }
        else
        {
            [self buttonClicked:2];
        }
    }];
}

//弹出信息
-(void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    showview.frame = CGRectMake((SCREEN_W - LabelSize.width - 20)/2, SCREEN_H - 300, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:1.5 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}


- (void)buttonClicked:(NSInteger )sender {
    AlertView *view;
    switch (sender) {
        case 1:
            view = [[AlertView alloc] initWithTitle:@"成功登陆正在跳转!!!" style:kAlertViewStyleSuccess showTime:kAlerViewShowTimeOneSecond];
            break;
        case 2:
            view = [[AlertView alloc] initWithTitle:@"您输入的验证码不正确!!!" style:kAlertViewStyleWarn showTime:kAlerViewShowTimeOneSecond];
            break;
        default:
            break;
    }
    [view showInView:self.view];
}


@end
